package com.yipin.neimeng.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

public class SignUtil {
    /**
     * 生成签名
     *
     * @param sysParamMap 系统参数Map
     * @param busiParam 业务参数字符串
     * @return 生成的签名
     * @throws Exception
     */
    public static String generateSign(Map<String, String> sysParamMap, String busiParam) throws Exception {
        // 对参数进行排序
        List<String> paramList = new ArrayList<>(sysParamMap.keySet());
        Collections.sort(paramList);

        // 将参数和业务参数值连接成一个字符串
        StringBuilder sb = new StringBuilder();
        for (String key : paramList) {
            String value = sysParamMap.get(key);
            if (value != null && !value.isEmpty()) {
                sb.append(key).append("=").append(value).append("&");
            }
        }
        sb.append("busiParam=").append(busiParam);

        // 使用SHA256算法生成签名（示例）
        String sign = sha256(sb.toString());
        return sign;
    }

    /**
     * 使用SHA256算法生成签名
     *
     * @param data 待签名字符串
     * @return SHA256签名
     * @throws NoSuchAlgorithmException
     */
    private static String sha256(String data) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hash = md.digest(data.getBytes(StandardCharsets.UTF_8));
        // 将字节转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
